package com.atsmart.app.sql;

import java.util.ArrayList;
import java.util.List;
import com.atsmart.app.model.TempleteSelectInfo;
import com.atsmart.app.model.TempleteSelectListInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

public class TemplateSelectSqlHelper {

	private SQLiteDatabase db = null;

	/**
	 * 打开数据库
	 */
	public void open(SqlHelper dh) {
		// dh = new SqlHelper(null, "atsmart", null,SqlHelper.getDBVersion());
		db = dh.getWritableDatabase();
	}

	public synchronized void addTemplateSelectInfo(TempleteSelectInfo at,
			int tem_id) {
		if (at == null) {
			return;
		}
		String strSql = "insert or replace into template_select_info (item_id,name,option) values(?,?,?);";
		try {
			SQLiteStatement stm = db.compileStatement(strSql);
			stm.bindLong(1, tem_id);
			stm.bindString(2, at.getName());
			stm.bindLong(3, at.getOption_id());
			stm.execute();
			stm.clearBindings();
			stm.close();
		} catch (Exception e) {
			e.printStackTrace();
			// will not happen
		}
	}

	public TempleteSelectListInfo getTemplateSelectInfo(int tem_id) {
		String sql = " select _id,item_id,name,option from template_select_info where item_id= "
				+ tem_id;
		Cursor cursor = db.rawQuery(sql, null);
		TempleteSelectInfo historie = null;
		List<TempleteSelectInfo> nums = null;
		TempleteSelectListInfo t = null;
		try {
			if (cursor != null && cursor.moveToFirst()) {
				nums = new ArrayList<TempleteSelectInfo>();
				t = new TempleteSelectListInfo();
				for (int i = 0; i < cursor.getCount(); i++) {
					historie = new TempleteSelectInfo();
					historie.setName(cursor.getString(2));
					historie.setOption_id(cursor.getInt(3));
					nums.add(historie);
					cursor.moveToNext();
				}
				t.setTemplates(nums);
			}
		} catch (Exception e) {
			return null;
		} finally {
			cursor.close();
		}
		return t;
	}

	public int getCount(int item_id) {
		String sql = "select _id from template_select_info where item_id=" + item_id;
		Cursor cursor = db.rawQuery(sql, null);
		try {
			if (cursor != null) {
				return cursor.getCount();
			}
		} catch (Exception e) {
			return -1;
		} finally {
			cursor.close();
		}
		return 0;
	}

	public void deleteAttribute() {
		// db.delete("position_attribute", null, null);
		db.execSQL("delete from template_select_info");
	}

	public void deleteByItemId(int item_id){
		db.execSQL("delete from template_select_info where item_id=" + item_id);
	}
}
